﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class LoopTaskSoure
    {
        private TaskCompletionSource<bool> TaskSource;
        private ConcurrentQueue<TaskCompletionSource<Task>> WaitTaskQueue;
        private ConcurrentQueue<int> NextQueue;

        public LoopTaskSoure(ConcurrentQueue<TaskCompletionSource<Task>> waitQueue) 
        {
            this.NextQueue = new ConcurrentQueue<int>();
            this.TaskSource = new TaskCompletionSource<bool>();
            this.WaitTaskQueue = waitQueue;
            Task.Run(LoopTaskAsync);
        }

        public void NextTask() 
        {
            if (!this.TaskSource.Task.IsCompleted)
            {
                this.TaskSource.TrySetResult(true);
            }
            else
            {
                this.NextQueue.Enqueue(0);
                //await Task.Delay(1);
                //this.NextTask();
            }
        }

        private async Task LoopTaskAsync() 
        {
            while (await this.TaskSource.Task)
            {
                if (this.WaitTaskQueue.TryDequeue(out TaskCompletionSource<Task> task))
                {
                    task.TrySetResult(Task.CompletedTask);
                }

                if (!this.NextQueue.TryDequeue(out _))
                {
                    this.TaskSource = new TaskCompletionSource<bool>();
                }
            }
        }

    }
}
